<template>
  <cl-dialog v-model="visible" class="zhongtian-add-order" width="90%" :close-on-click-modal="false">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>镜片订单添加</span>
        </div>
      </template>
      <el-form ref="formRef" :model="formData" label-width="120px">

        
        
        <!-- 验光数据（可选） -->
        <el-divider content-position="left">镜片数据</el-divider>
        
            
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="左镜片" prop="data.o.c_goods_l">
                <div class="inline-flex-container">
                <el-select v-if="goodsList.length > 0" v-model="formData.c_goods_l" placeholder="请选择镜片" style="width: auto; min-width: 300px; margin-right: 8px;">
                    <el-option v-for="item in goodsList" :key="item.lens_code" :label="item.lens_desc" :value="item.lens_code" />
                </el-select>
                <div style="display: flex; align-items: center;">
                    <span style="margin-right: 4px;">数量：</span>
                    <el-input v-model="formData.c_lnum" placeholder="请输入采购数量" style="width: 100px;" />
                </div>
                </div>
            </el-form-item>
            </el-col>

            <el-col :span="12">
                <el-form-item label="左镜片" prop="data.o.c_goods_r">
                    <div class="inline-flex-container">
                        <el-select v-if="goodsList.length > 0" v-model="formData.c_goods_r" placeholder="请选择镜片" style="width: auto; min-width: 300px; margin-right: 8px;">
                            <el-option v-for="item in goodsList" :key="item.lens_code" :label="item.lens_desc" :value="item.lens_code" />
                        </el-select>
                        <div style="display: flex; align-items: center;">
                            <span style="margin-right: 4px;">数量：</span>
                            <el-input v-model="formData.c_rnum" placeholder="请输入采购数量" style="width: 100px;" />
                        </div>
                    </div>
                </el-form-item>
            </el-col>
          <el-col :span="12">
            <el-form-item label="左直径R" prop="data.o.c_dial">
              <el-input v-model="formData.c_dial" placeholder="例子：60" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="右直径R" prop="data.o.c_diar">
              <el-input v-model="formData.c_diar" placeholder="例子：60" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="左球镜" prop="data.o.c_lball">
              <el-input v-model="formData.c_lball" placeholder="例子：-500" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="右球镜" prop="data.o.c_rball">
              <el-input v-model="formData.c_rball" placeholder="例子：-500" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="左柱镜" prop="data.o.c_lpole">
              <el-input v-model="formData.c_lpole" placeholder="例子：-150" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="右柱镜" prop="data.o.c_rpole">
              <el-input v-model="formData.c_rpole" placeholder="例子：-150" />
            </el-form-item>
          </el-col>

          

          <el-col :span="12">
            <el-form-item label="左下加光" prop="data.o.c_ladd">
              <el-input v-model="formData.c_ladd" placeholder="例子：100" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="右下加光" prop="data.o.c_radd">
              <el-input v-model="formData.c_radd" placeholder="例子：100" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="左线轴" prop="data.o.c_lpole">
              <el-input v-model="formData.c_lline" placeholder="例子：179" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="右线轴" prop="data.o.c_rpole">
              <el-input v-model="formData.c_rline" placeholder="例子：179" />
            </el-form-item>
          </el-col>

          <!-- 是否加工 -->
          <el-col :span="12">
            <el-form-item label="是否加工" prop="data.o.c_is_process">
              <el-radio-group v-model="formData.c_is_process" @change="handleChange">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

        </el-row>
        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="checkForm">检查订单</el-button>
          <el-button type="primary" :disabled="!checkOrder" @click="submitForm">提交订单</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="closeDialog">关闭</el-button>
        </div>
      </el-form>
    </el-card>
  </cl-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';

const { service } = useCool();
const { t } = useI18n();
const formRef = ref();
const visible = ref(false);
const emit = defineEmits(['closeDialog', 'update:modelValue',]);

const props = defineProps({
  orderId: {
    type: Number,
    default: 0
  },
  modelValue: {
        type: Boolean,
        default: false
    }
})

// 表单数据
const formData = reactive({
    c_dial: '60',
    c_diar: '60',
    c_lball: '-500',
    c_rball: '-500',
    c_lpole: '-150',
    c_rpole: '-150',
    c_goods_l: '',
    c_goods_r: '',
    c_goods_left_list: [],
    c_goods_right_list: [],
    c_lnum: 1,
    c_rnum: 1,
    c_ladd: '100',
    c_radd: '100',
    c_lline: '179',
    c_rline: '179',
    c_goods_l_desc: '',
    c_goods_r_desc: '',
    order_id: props.orderId
});
const c_goods_left_list = ref([])
const c_goods_right_list = ref([])

// 获取商品列表
async function getGoodsList(c_ball, c_pole, type) {
  const res = await service.order.merchant.getGoodsList({
    c_ball,
    c_pole
  })
  if (res.length <= 0) {
    ElMessage.error('没有符合要求的镜片')
    return
  }
    if (type == 'left') {
        c_goods_left_list.value = res
    } else if (type == 'right') {
        c_goods_right_list.value = res
    }
  
  console.log('获取商品列表', res)
}
const checkOrder = ref(false)

// 检查订单
async function checkForm() {
    if (formData.c_goods_l == '' || formData.c_goods_r == '') {
        ElMessage.error('请选择镜片')
        return
    }
    if (formData.c_dial == '' || formData.c_diar == '' || formData.c_lball == '' || formData.c_rball == '' || formData.c_lpole == '' || formData.c_rpole == '' || formData.c_ladd == '' || formData.c_radd == '' || formData.c_lline == '' || formData.c_rline == '') {
        ElMessage.error('请填写完整订单信息')
        return
    }
    checkOrder.value = true
}


// 提交表单
async function submitForm() {
    if (!checkOrder.value) {
        ElMessage.error('请先检查订单')
        return
    }
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    // 这里是提交表单的逻辑，调用API提交数据
    console.log('提交的表单数据:', formData);
    if (formData.c_goods_l == '' || formData.c_goods_r == '') {
        ElMessage.error('请选择镜片')
        return
    }
    // 根据code找到镜片的desc
    let goods_l_desc = ''
    let goods_r_desc = ''
    goodsList.value.forEach(item => {
        if (item.lens_code == formData.c_goods_l) {
            goods_l_desc = item.lens_desc
        }
        if (item.lens_code == formData.c_goods_r) {
            goods_r_desc = item.lens_desc
        }
    })
    formData.c_goods_l_desc = goods_l_desc
    formData.c_goods_r_desc = goods_r_desc
    formData.order_id = props.orderId
    // 模拟API调用
    // 实际项目中应替换为真实的API调用
    const res = await service.order.merchant.submitTongkangOrder(formData);
    console.log(res)
    // 模拟提交成功
    ElMessage.success('订单添加成功');
    
    // 关闭弹窗
    closeDialog();
  } catch (error) {
    console.error('表单验证失败:', error);
    ElMessage.error(error.message);
  }
}

const goodsList = ref([])

async function getTongkangGoods()
{
    goodsList.value = await service.order.merchant.getTongkangGoodsList()
}

// 重置表单
function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields();
    // 重置普通字段
    formData.c_lball = '';
    formData.c_rball = '';
    formData.c_lpole = '';
    formData.c_rpole = '';
    formData.c_goods_l = '';
    formData.c_goods_r = '';
    formData.c_goods_left_list = [];
    formData.c_goods_right_list = [];
    formData.c_lnum = 1;
    formData.c_rnum = 1;
    formData.c_ladd = '';
    formData.c_radd = '';
    formData.c_lline = '';
    formData.c_rline = '';
  }
}

// 关闭弹窗
function closeDialog() {
    console.log('props.currentOrderId', props.orderId, visible.value)
    emit('closeDialog')
}

async function syncGoods() {
  const res = await service.order.merchant.getGoodsType()
  console.log(res);
}

// 监听 modelValue 变化
watch(
	() => props.modelValue,
	val => {
        console.log('弹窗', val, props.orderId)
        if (val) {
            // getGoodsList()
            getTongkangGoods()
        }
		visible.value = val;
	}
);

// 监听 visible 变化
watch(
	() => visible.value,
	val => {
		emit('update:modelValue', val);
		if (!val) {
			resetForm();
		}
	}
);



</script>

<style scoped>
.zhongtian-add-order {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-item,
.payment-item {
  margin-bottom: 20px;
}

.detail-header,
.payment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.border-top-blue {
  border-top: 3px solid #409eff;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.form-actions .el-button {
  margin: 0 10px;
}

/* 添加新的样式类 */
.inline-flex-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
</style>